package com.kaige.asktaoplugin60.utils;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

/**
 * 十六进制工具类
 */
public class HexUtil {
    
    private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
    
    /**
     * 将字节数组转换为十六进制字符串
     * 
     * @param bytes 字节数组
     * @return 十六进制字符串，例如: "4D 5A 00 00 00 20 67 F5"
     */
    public static String bytesToHex(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return "";
        }
        
        StringBuilder hexString = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            if (i > 0) {
                hexString.append(" ");
            }
            int v = bytes[i] & 0xFF;
            hexString.append(HEX_ARRAY[v >>> 4]);
            hexString.append(HEX_ARRAY[v & 0x0F]);
        }
        return hexString.toString();
    }

    /**
     * 将十六进制字符串转换为字节数组
     *
     * @param hexString 十六进制字符串，例如: "4D 5A 00 00 00 20 67 F5"
     * @return 字节数组
     */
    public static byte[] hexToBytes(String hexString) {
        if (hexString == null || hexString.isEmpty()) {
            return new byte[0];
        }

        hexString = hexString.replaceAll("\\s+", "");
        int length = hexString.length();
        byte[] bytes = new byte[length / 2];
        for (int i = 0; i < length; i += 2) {
            bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
        }
        return bytes;
    }

    /**
     * 将ByteBuf转换为十六进制字符串
     */
    public static String byteBufToHex(ByteBuf byteBuf) {
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.getBytes(byteBuf.readerIndex(), bytes);
        return bytesToHex(bytes);
    }


    /**
     * 将十六进制字符串转换为ByteBuf
     */
    public static ByteBuf hexToByteBuf(String s) {
        return Unpooled.wrappedBuffer(hexToBytes(s));
    }

    /**
     * 获取包头
     */
    public static ByteBuf getFinalPacket(ByteBuf buf) {
        ByteBuf byteBuf = Unpooled.buffer().writeBytes(hexToBytes("4D 5A 00 00 00 00 00 00"));
        byteBuf.writeShort(buf.readableBytes());
        return Unpooled.wrappedBuffer(byteBuf, buf);
    }

}